package day16.tarena.mycalculator;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * @author Peihu.Wang
 */
public class Calculator implements ActionListener {
	String[] num = {"" ,"" ,""};		
	JTextField jt = new JTextField(0);
	
	public void actionPerformed(ActionEvent e) {
		String n = e.getActionCommand();
		jt.setText(n);
		if("+".equals(n)){
			jt.setText(n);
			num[2] = n;						//	If this symbol is "+" 
		}else if("-".equals(n)){
			jt.setText(n);
			num[2] = n;									
		}else if("*".equals(n)){
			jt.setText(n);
			num[2] = n;
		}else if("/".equals(n)){
			jt.setText(n);
			num[2] = n;
		}else if("CE".equals(n)){
			jt.setText(0+"");
			num[0] = "";
			num[1] = "";
			num[2] = "";
		}else if("C".equals(n)){
			jt.setText(0+"");
			num[0] = "";
			num[1] = "";
			num[2] = "";
		}else if("=".equals(n)){
			if("+".equals(num[2])){
				jt.setText(Float.parseFloat(num[0]) + Float.parseFloat(num[1])+"");		
			}else if("-".equals(num[2])){
				jt.setText(Float.parseFloat(num[0]) - Float.parseFloat(num[1])+"");
			}else if("*".equals(num[2])){
				jt.setText(Float.parseFloat(num[0]) * Float.parseFloat(num[1])+"");
			}else if("/".equals(num[2])){
				jt.setText(Float.parseFloat(num[0]) / Float.parseFloat(num[1])+"");
			}
		}else {
			if(num[2] == ""){
				num[0] =num[0] +n;
				jt.setText(num[0]+"");
			}else{
				num[1] =num[1] +n;
				jt.setText(num[1]+"");
			}
		}
	}
	
	public static void main(String[] args) {
		new Calculator();
	}
	
	public Calculator(){
		JFrame jf = new JFrame("Calculator");
	
		jf.add(jt,BorderLayout.NORTH);
		JPanel jp = new JPanel();
		GridLayout gl = new GridLayout(5,4);
		String[] lab = {"BackS","CE","C","+",
							"7","8","9","-",
							"4","5","6","*",
							"1","2","3","/",
							"0","+/-",".","="};
		jp.setLayout(gl);
		for(int i=0;i<lab.length;i++){
			JButton jb = new JButton(lab[i]);
			jb.addActionListener(this);	
			jp.add(jb);
		}
		jf.add(jp);
		jf.setLocation(300,200);			
		jf.setSize(400,300);				
		jf.setResizable(false);
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
